package com.zf.flink.simple;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * Spring 管理的数据源工具类，避免硬编码数据库连接信息
 */
@Component
public class DataSourceUtil {
    private static ApplicationContext applicationContext;

    @Autowired
    public void setApplicationContext(ApplicationContext context) {
        DataSourceUtil.applicationContext = context;
    }

    /**
     * 获取数据库连接 (通过 Spring 数据源)
     */
    public static Connection getConnection() {
        DataSource dataSource = applicationContext.getBean(DataSource.class);
        return DataSourceUtils.getConnection(dataSource);
    }
}